<template>
  <div class="violation-bg">
    <el-card class="violation-card">
      <div class="violation-header">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <div class="violation-title">车辆违章记录</div>
        <el-button type="primary" @click="showAddDialog" icon="Plus">添加违章记录</el-button>
      </div>

      <div v-if="loading" class="loading-container">
        <el-loading-spinner />
        <p>加载中...</p>
      </div>

      <div v-else-if="violationList.length === 0" class="empty-container">
        <el-empty description="暂无违章记录">
          <el-button type="primary" @click="showAddDialog">立即添加</el-button>
        </el-empty>
      </div>

      <div v-else class="violation-list">
        <el-table :data="violationList" style="width: 100%">
          <el-table-column prop="violation_time" label="违章时间" width="180">
            <template #default="scope">
              {{ formatTime(scope.row.violation_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="location" label="违章地点" width="200" show-overflow-tooltip />
          <el-table-column prop="violation_type" label="违章类型" width="150" />
          <el-table-column prop="penalty_amount" label="罚款金额" width="100">
            <template #default="scope">
              <span v-if="scope.row.penalty_amount">¥{{ scope.row.penalty_amount }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="penalty_points" label="扣分" width="80">
            <template #default="scope">
              <span v-if="scope.row.penalty_points">{{ scope.row.penalty_points }}分</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="处理状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
                {{ scope.row.status === 1 ? '已处理' : '未处理' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="viewDetail(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click="editViolation(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteViolation(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加/编辑对话框 -->
      <el-dialog 
        v-model="dialogVisible" 
        :title="isEdit ? '编辑违章记录' : '添加违章记录'"
        width="600px"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="车辆" prop="vehicle">
            <el-select v-model="form.vehicle" placeholder="请选择车辆" style="width: 100%">
              <el-option 
                v-for="vehicle in vehicleList" 
                :key="vehicle.id" 
                :label="vehicle.plate_number" 
                :value="vehicle.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="违章时间" prop="violation_time">
            <el-date-picker
              v-model="form.violation_time"
              type="datetime"
              placeholder="选择违章时间"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="违章地点" prop="location">
            <el-input v-model="form.location" placeholder="请输入违章地点" />
          </el-form-item>

          <el-form-item label="违章类型" prop="violation_type">
            <el-select v-model="form.violation_type" placeholder="请选择违章类型" style="width: 100%">
              <el-option label="超速行驶" value="超速行驶" />
              <el-option label="闯红灯" value="闯红灯" />
              <el-option label="违章停车" value="违章停车" />
              <el-option label="不按规定车道行驶" value="不按规定车道行驶" />
              <el-option label="未系安全带" value="未系安全带" />
              <el-option label="使用手机" value="使用手机" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>

          <el-form-item label="罚款金额" prop="penalty_amount">
            <el-input-number 
              v-model="form.penalty_amount" 
              :precision="2" 
              :min="0" 
              placeholder="请输入罚款金额"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="扣分" prop="penalty_points">
            <el-input-number 
              v-model="form.penalty_points" 
              :min="0" 
              :max="12"
              placeholder="请输入扣分"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="处理状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="0">未处理</el-radio>
              <el-radio :label="1">已处理</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ submitLoading ? '保存中...' : '确定' }}
          </el-button>
        </template>
      </el-dialog>

      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="违章记录详情" width="500px">
        <div v-if="selectedViolation" class="violation-detail">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="车辆">
              {{ getVehiclePlateNumber(selectedViolation.vehicle) }}
            </el-descriptions-item>
            <el-descriptions-item label="违章时间">
              {{ formatTime(selectedViolation.violation_time) }}
            </el-descriptions-item>
            <el-descriptions-item label="违章地点">
              {{ selectedViolation.location || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="违章类型">
              {{ selectedViolation.violation_type }}
            </el-descriptions-item>
            <el-descriptions-item label="罚款金额">
              {{ selectedViolation.penalty_amount ? `¥${selectedViolation.penalty_amount}` : '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="扣分">
              {{ selectedViolation.penalty_points ? `${selectedViolation.penalty_points}分` : '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="处理状态">
              <el-tag :type="selectedViolation.status === 1 ? 'success' : 'warning'">
                {{ selectedViolation.status === 1 ? '已处理' : '未处理' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatTime(selectedViolation.created_at) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { vehicleViolationAPI, vehicleAPI } from '@/api/vehicle'

const router = useRouter()
const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref()

const violationList = ref([])
const vehicleList = ref([])
const selectedViolation = ref(null)

// 表单数据
const form = ref({
  vehicle: '',
  violation_time: '',
  location: '',
  violation_type: '',
  penalty_amount: null,
  penalty_points: null,
  status: 0
})

// 表单验证规则
const rules = {
  vehicle: [
    { required: true, message: '请选择车辆', trigger: 'change' }
  ],
  violation_time: [
    { required: true, message: '请选择违章时间', trigger: 'change' }
  ],
  violation_type: [
    { required: true, message: '请选择违章类型', trigger: 'change' }
  ]
}

onMounted(() => {
  fetchViolationList()
  fetchVehicleList()
})

// 获取违章记录列表
async function fetchViolationList() {
  try {
    loading.value = true
    const userId = localStorage.getItem('userid')
    const response = await vehicleViolationAPI.getViolationList({ user_id: userId })
    violationList.value = response.data || []
  } catch (error) {
    console.error('获取违章记录失败:', error)
    ElMessage.error('获取违章记录失败')
  } finally {
    loading.value = false
  }
}

// 获取车辆列表
async function fetchVehicleList() {
  try {
    const userId = localStorage.getItem('userid')
    const response = await vehicleAPI.getVehicles({ user_id: userId })
    vehicleList.value = response.data || []
  } catch (error) {
    console.error('获取车辆列表失败:', error)
  }
}

// 显示添加对话框
function showAddDialog() {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑违章记录
function editViolation(violation) {
  isEdit.value = true
  form.value = {
    id: violation.id,
    vehicle: violation.vehicle,
    violation_time: new Date(violation.violation_time),
    location: violation.location || '',
    violation_type: violation.violation_type,
    penalty_amount: violation.penalty_amount,
    penalty_points: violation.penalty_points,
    status: violation.status
  }
  dialogVisible.value = true
}

// 查看详情
function viewDetail(violation) {
  selectedViolation.value = violation
  detailDialogVisible.value = true
}

// 删除违章记录
async function deleteViolation(violation) {
  try {
    await ElMessageBox.confirm(
      `确定要删除这条违章记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await vehicleViolationAPI.deleteViolation(violation.id)
    ElMessage.success('删除成功')
    fetchViolationList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
async function submitForm() {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    const submitData = {
      vehicle: form.value.vehicle,
      violation_time: form.value.violation_time,
      location: form.value.location,
      violation_type: form.value.violation_type,
      penalty_amount: form.value.penalty_amount,
      penalty_points: form.value.penalty_points,
      status: form.value.status
    }

    if (isEdit.value) {
      await vehicleViolationAPI.updateViolation(form.value.id, submitData)
      ElMessage.success('修改成功')
    } else {
      await vehicleViolationAPI.createViolation(submitData)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchViolationList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
function resetForm() {
  form.value = {
    vehicle: '',
    violation_time: '',
    location: '',
    violation_type: '',
    penalty_amount: null,
    penalty_points: null,
    status: 0
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 格式化时间
function formatTime(time) {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 获取车辆车牌号
function getVehiclePlateNumber(vehicleId) {
  const vehicle = vehicleList.value.find(v => v.id === vehicleId)
  return vehicle ? vehicle.plate_number : '-'
}

// 返回上一页
function goBack() {
  router.back()
}
</script>

<style scoped>
.violation-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.violation-card {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.violation-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.violation-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.loading-container, .empty-container {
  padding: 60px 20px;
  text-align: center;
  color: #666;
}

.violation-list {
  padding: 24px;
}

.violation-detail {
  padding: 16px 0;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}
</style>
